This example demonstrates how to send an SMS text message from an Android App.
-----------------------------------------
1. Create the layout - activity_main.xml
-----------------------------------------
---------------------------
2. Update MainActivity.java
---------------------------
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends Activity {
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
Button sendSMSBtn;
EditText toPhoneNumberET;
EditText smsMessageET;
String phoneNo;
String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendSMSBtn = (Button) findViewById(R.id.SendSMS);
toPhoneNumberET = (EditText) findViewById(R.id.editTextPhoneNo);
smsMessageET = (EditText) findViewById(R.id.editTextSMS);
sendSMSBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
protected void sendSMSMessage() {
phoneNo = toPhoneNumberET.getText().toString();
message = smsMessageET.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS failed, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
-----------------------------------------------------------
3. Need to add SEND_SMS permission to the android manifest
-----------------------------------------------------------